package com.example.blueconn.manager;

import android.graphics.Color;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.lifecycle.MutableLiveData;

import com.example.blueconn.R;
import com.example.blueconn.views.MyMarkerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChartMgr {

    private static final String TAG = "ChartMgr";

    private static final ChartMgr chartMgr = new ChartMgr();
    //根据deviceNumb来绑定LineData
    private static final Map<Integer, List<LineData>> chartDataMap = new HashMap<>();
    private static final MutableLiveData<Integer> chartRefresh = new MutableLiveData<>();


    public static final int LIGHT_TYPE = 0;
    public static final int TEMP_TYPE = 1;
    private static final Map<Integer, LineData> lightDataMap = new HashMap<>();
    private static final Map<Integer, LineData> tempDataMap = new HashMap<>();

    //chart数据相关
    private static final String[] chartColor = new String[]{"#8B1A1A", "#008B8B", "#698B69", "#5D478B"};

    private ChartMgr() {

    }

    public static ChartMgr getInstance() {
        return chartMgr;
    }

    @UiThread
    public void initChartObserver() {

        DataMgr.getRealTempData().observeForever(tempData -> {
            if (tempData != null) {
                if (tempDataMap.isEmpty()) {
                    for (int i = 0; i < 5; i++) {
                        LineData lineData = new LineData();
                        ILineDataSet dataSet = lineData.getDataSetByIndex(i);
                        if (dataSet == null) {
                            dataSet = createSetByLabel(i, "温度");
                            dataSet.addEntry(new Entry(dataSet.getEntryCount(), tempData.getTempByIndex(i)));
                        }
                        lineData.addDataSet(dataSet);
                        tempDataMap.put(i, lineData);
                    }
                } else {
                    for (int i = 0; i < 5; i++) {
                        LineData lineData = tempDataMap.get(i);
                        if (lineData == null) {
                            return;
                        }
                        ILineDataSet lightDataSet = lineData.getDataSetByIndex(0);
                        lightDataSet.addEntry(new Entry(lightDataSet.getEntryCount(), tempData.getTempByIndex(i)));
                    }
                }

                for (LineData data : tempDataMap.values()) {
                    data.notifyDataChanged();
                }
            }

            DataMgr.getTempRefresh().postValue(true);
        });

        DataMgr.getRealLightData().observeForever(lightData -> {
            if (lightData != null) {
                if (lightDataMap.isEmpty()) {
                    for (int i = 0; i < 6; i++) {
                        LineData lineData = new LineData();
                        ILineDataSet dataSet = lineData.getDataSetByIndex(0);
                        ILineDataSet dataSet2 = lineData.getDataSetByIndex(1);
                        if (dataSet == null) {
                            dataSet = createSetByLabel(i, "照度1");
                            dataSet.addEntry(new Entry(dataSet.getEntryCount(), lightData.getLightByIndex(i, true)));
                            lineData.addDataSet(dataSet);
                        }
                        if (dataSet2 == null) {
                            dataSet2 = createSetByLabel(i + 1, "照度2");
                            dataSet2.addEntry(new Entry(dataSet2.getEntryCount(), lightData.getLightByIndex(i, false)));
                            lineData.addDataSet(dataSet2);
                        }
                        lightDataMap.put(i, lineData);
                    }
                } else {
                    for (int i = 0; i < 6; i++) {
                        LineData lineData = lightDataMap.get(i);
                        if (lineData == null) {
                            return;
                        }
                        ILineDataSet lightDataSet = lineData.getDataSetByIndex(0);
                        lightDataSet.addEntry(new Entry(lightDataSet.getEntryCount(), lightData.getLightByIndex(i, true)));
                        ILineDataSet lightDataSet2 = lineData.getDataSetByIndex(1);
                        lightDataSet2.addEntry(new Entry(lightDataSet2.getEntryCount(), lightData.getLightByIndex(i, false)));
                    }
                }

                for (LineData data : lightDataMap.values()) {
                    data.notifyDataChanged();
                }
            }

            DataMgr.getLightRefresh().postValue(true);
        });
    }

    public static LineData getLightLineDataByDevice(int number) {
        return lightDataMap.get(number);
    }

    public static LineData getTempLineDataByDevice(int number) {
        return tempDataMap.get(number);
    }

    public static MutableLiveData<Integer> getChartRefresh() {
        return chartRefresh;
    }

    public void initChart(@NonNull LineChart chart, int index, int type) {
        Description description = new Description();
        description.setText("通道:No" + (index + 1));
        description.setTextSize(12);
        chart.setDescription(description);

        chart.setNoDataText("暂时尚无数据");
        chart.setTouchEnabled(true);
        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setPinchZoom(true);
        chart.setBackgroundColor(Color.LTGRAY);
        MyMarkerView markerView = new MyMarkerView(chart.getContext(), R.layout.custom_marker_view);
        markerView.setChartView(chart);
        chart.setMarker(markerView);

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);

        //数据配置
        LineData lineData;
        if (type == LIGHT_TYPE) {
            lineData = lightDataMap.get(index);
        } else {
            lineData = tempDataMap.get(index);
        }
        if (lineData != null) {
            chart.setData(lineData);
        }
//        chart.setData(chartDataMap.get(deviceNum));

        //X轴配置
        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setAvoidFirstLastClipping(false);
        xAxis.setEnabled(true);

        //左边Y轴
        YAxis left = chart.getAxisLeft();
        left.setTextColor(Color.parseColor(chartColor[type]));

        //右边Y轴
        YAxis right = chart.getAxisRight();
        right.setTextColor(Color.parseColor(chartColor[type]));
    }

    private static ILineDataSet createSetByLabel(int i, String label) {
        LineDataSet set = new LineDataSet(null, label);
//        if (i == 1) {
//            set.setAxisDependency(YAxis.AxisDependency.RIGHT);
//        } else {
//            set.setAxisDependency(YAxis.AxisDependency.LEFT);
//        }
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(Color.parseColor(chartColor[i % chartColor.length]));
        set.setLineWidth(2f);
        set.setCircleColor(Color.WHITE);
        set.setCircleRadius(2f);
//        set.setDrawCircles(false);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setHighlightEnabled(true);
        set.setValueTextColor(Color.BLACK);
        set.setValueTextSize(9f);
        set.setDrawValues(false);
        return set;
    }

    /**
     * 清理所有数据
     */
    public static void clearChartData() {
        Collection<List<LineData>> values = chartDataMap.values();
        for (List<LineData> value : values){
            if (value != null) {
                for (LineData data : value) {
//                    data.clearValues();
                    List<ILineDataSet> dataSets = data.getDataSets();
                    for (ILineDataSet set : dataSets) {
                        set.clear();
                    }
                }
            }
        }
    }

    /**
     * 根据设备进行数据清理
     */
    public static void clearDeviceData(int deiceNum) {
        List<LineData> lineData = chartDataMap.get(deiceNum);
        if (lineData != null) {
            for (LineData data : lineData) {
//                data.clearValues();
                try {
                    Class clazz = data.getClass().getSuperclass().getSuperclass();
                    Field field = clazz.getDeclaredField("mXMax");
                    field.setAccessible(true);
                    field.set(data, 0);
                    Log.i("dayinxzhou", "设置属性ok");
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                    Log.e("dayinxzhou", "异常了: " + e.getMessage());
                }
                List<ILineDataSet> dataSets = data.getDataSets();
                for (ILineDataSet set : dataSets) {
                    set.clear();
                    Log.i("dayinxzhou", "清理时，entryCount : " + set.getEntryCount());
                }
            }
        }
    }
}
